/**
 * Created by weng on 2017/9/2.
 * 这一块是用数据来控制视图的模块
 */
define(function (require) {
    var userModel = require("userHandler");
    var toast = require("toastDom");
    var $ = require("jquery");
    require("jquery.cookie");
    //人员权限
    if($.cookie('type')=='teacher'){
        var userHandler =userModel.TeacherHandler;
    }else{
        var userHandler =userModel.StudentHandler;
    }

    var user = new userHandler();
    var v_list;
//模拟登陆，这是在其他登陆页面没有写完的时候测试使用，最后删掉即可
//     function logintestModel() {
        // user.login({username:'gzq9425',password:'123'},function(){
        //     $.cookie('courseId',1,{path: '/'});
        //     console.log($.cookie('courseId'))
        // })
        // user.login({username:'ggg',password:'123'},function(){
        //     user.joinCourse(1,function () {
        //         $.cookie('courseId',1,{path: '/'});
        //         console.log($.cookie('courseId'))
        //     })
        //
        // })

    // }
    // logintestModel();
    var courseId = $.cookie('courseId');
    var _question=[];
    //事件绑定
    function eventBinding() {
        if(document.getElementById('left-side')){
            var close_btn = document.getElementById('left-side').getElementsByClassName('close');
            removeEvent(close_btn,deleteNotice);
            bindingFunction(close_btn,deleteNotice);
        }

        var download_btn = document.getElementsByClassName('download-btn');
        removeEvent(download_btn,downloadFile);
        bindingFunction(download_btn,downloadFile);
        if(document.getElementById('center-side')){
            // var stop_btn = document.getElementById('center-side').getElementsByClassName('close');
            // bindingFunction(stop_btn,endVote);
        // }else{
            var up_answer = document.getElementById('center-side').getElementsByClassName('up_answer');
            removeEvent(up_answer,studentAnswer);
            bindingFunction(up_answer,studentAnswer);
        }
        if(document.getElementById('question')){
            var up_an = document.getElementById('question').getElementsByClassName('up_answer');
            removeEvent(up_an,m_studentAnswer);
            bindingFunction(up_an,m_studentAnswer);
        }


    }
    //遍历绑定
    function bindingFunction(node,fun) {
        for(var i =0;i<node.length;i++){
            node[i].onclick=
                (function () {
                    var ind = i;
                    var index = node[ind].parentNode.parentNode.dataset.idx;
                    if(index==undefined) index=node[ind].parentNode.parentNode.parentNode.dataset.idx;
                    var filename = node[ind].parentNode.parentNode.dataset.filename;
                    var filePath = node[ind].parentNode.parentNode.dataset.path;

                    return ()=>fun(index,filename,filePath);
                })(i)

        }
        // console.log('bind success')
    }
    function removeEvent(node, fun) {
        for(var i =0;i<node.length;i++){
            node[i].removeEventListener('click',
                fun)
        }
        // console.log('remove success')
    }


    //common权限
    function showNotice(courseId) {
        toast.showMsg('正在获取信息列表',1000);

        return user.getNotice(courseId,function (data) {
            var left_list = document.getElementById('left-side');
            var data_reverse = data.reverse();
            var list ='';
            data_reverse.map((item,index)=>{
                list +=`<div class="card" data-idx=${item.id}>
                            <div class="card-title">${item.date.substring(0,10)} <span class="close">X</span></div>
                            <div class="card-content">&nbsp;&nbsp;${item.content}</div>
                        </div>`
            });
            left_list.innerHTML = list;
            eventBinding();
        })
    }

    function m_showNotice(courseId) {
        toast.showMsg('正在获取信息列表',1000);

        return user.getNotice(courseId,function (data) {
            var left_list = document.getElementById('bulletin');
            var data_reverse = data.reverse();
            var list ='';
            data_reverse.map((item,index)=>{
                list +=`
                    <div class="content" data-idx=${item.id}>
                        <div class="content-time">${item.date.substring(0,10)}</div>
                        <div class="content-inner">&nbsp;&nbsp;${item.content}</div>
                    </div>`
            });
            left_list.innerHTML = list;
        })
    }

    function showFile(courseId) {
        user.getCourseFile(courseId,function (data) {
            // console.log(data);
            var right_side = document.getElementById('right-side');
            var data_list = data;
            var file_list = '';
            data_list.map((item,index)=>{
                file_list +=`<div class="card" data-idx=${item.id} data-filename=${item.fileName} data-path=${item.path}>
                                <div class="card-head">${item.fileName} <span class="gray-word">${formatSize(item.size)}</span></div>
                                <div class="card-btn">
                                    <!--<img src="image/cancel.png" alt="">-->
                                    <img src="image/download.png" class="download-btn" alt="">
                                </div>
                            </div>`
            });
            right_side.innerHTML = file_list;
            eventBinding();
        })

    }
    function m_showFile(courseId) {
        user.getCourseFile(courseId,function (data) {
            // console.log(data);
            var right_side = document.getElementById('resource');
            var data_list = data;
            var file_list = '';
            data_list.map((item,index)=>{
                file_list +=`
                            <div class="content flex-content" data-idx=${item.id} data-filename=${item.fileName} data-path=${item.path}>
                                <div class="content-name">${item.fileName}</div>
                                <div class="content-small">${formatSize(item.size)}</div>
                                <span><img class="content-img download-btn" src="image/download.png" alt="下载"></span>
                            </div>`
            });
            right_side.innerHTML = file_list;
            eventBinding();
        })
    }

    function downloadFile(fileId,filename,filePath) {
        user.downloadCourseFile(fileId,filename,filePath);
        // console.log(fileId)

    }





    function uploadFile(courseId) {
        toast.showMsg('正在上传');
        user.uploadCourseFile(courseId,document.getElementById("btn_file").files[0],function () {
            toast.removeMsg();
            document.getElementById('fileShow').innerText = '上传成功';
            setTimeout(closeMode,1000);

            showFile(courseId);
        })
    }


    //老师权限
    function postNotice(courseId) {
        var content = document.getElementById('mode-content').value;
        var obj ={
            content:content
        }
        console.log(content);
        user.uploadNotice(courseId,obj,function () {
            showNotice(courseId);

        });
    }
    function deleteNotice(noticeId) {
        console.log(noticeId);
        user.deleteNotice(noticeId,function () {
            showNotice($.cookie('courseId'));
        })
    }
    function teacherGetVote(courseId) {
        user.teacherGetVoteList(courseId,function (data) {
            // console.log(data);
            var center_side = document.getElementById('center-side');
            var data_list = data!=undefined?data.reverse():data;
            v_list = '';
            data_list.map((item,index)=>{
                _question[index] ={id:item.id,answerCount:item.answerCount}
                var anwer_list ='';
                item.answerCount.map((itm,idx)=>{
                    anwer_list +=`<li><span>${itm.answer}</span>${itm.count}人</li>`
                });
                v_list +=`<div class="card" data-idx=${item.id}>
                            <div class="card-title big-font">${item.question}</div>
                            <div class="card-content">
                                <ul class="options">
                                
                                    ${anwer_list}
            
                                </ul>
                            </div>
                        </div>`
                center_side.innerHTML = v_list;

            })
        })
    }
    function startVote(courseId) {
        var v_content = document.getElementById('mode-content').value;
        var center_side = document.getElementById('center-side');
        user.startVote(courseId,v_content,function (data) {
            console.log(data);
            v_list =`<div class="card" data-idx=${data.id}>
                            <div class="card-title big-font">${v_content}</div>
                            <div class="card-content">
                                <ul class="options">
                                </ul>
                            </div>
                        </div>`+v_list;
            center_side.innerHTML = v_list;
        })
    }
    function endVote(vid) {
        user.endVote(vid,function () {
            console.log(vid);
            $(`#center-side .card[data-idx=${vid}] .close`).unbind().addClass('gray-word');
        })

    }







    //学生权限
    function studentGetVote(courseId) {
        user.studentGetVoteList(courseId,function (data) {
            console.log(data);
            var center_side = document.getElementById('center-side');
            var data_list = data.reverse();
            var list = '';
            data_list.map((item,index)=>{
                if(item.answer!=null){
                    list +=`<div class="card" data-idx=${item.id}>
                            <div class="card-title big-font">${item.question}</div>
                            <div class="card-content">
                                <ul class="options">
                                    <li><span>我的答案是：</span>${item.answer}</li>
                                </ul>
                            </div>
                        </div>`
                }else{
                    list +=`<div class="card" data-idx=${item.id}>
                            <div class="card-title big-font">${item.question}</div>
                            <div class="card-content">
                                 <ul class="options options-s">
                                    <input class="answer_input" type="text" placeholder="请输入你的答案">
                                    <img class="up_answer" src="image/upload.png" alt="">
                                </ul>
                            </div>
                        </div>`
                }

                center_side.innerHTML = list;

            })
            eventBinding()
        })
    }

    function m_studentGetVote(courseId) {
        user.studentGetVoteList(courseId,function (data) {
            console.log(data);
            var center_side = document.getElementById('question');
            var data_list = data.reverse();
            var list = '';
            data_list.map((item,index)=>{
                if(item.answer!=null){
                    list +=`
                            <div class="content" data-idx=${item.id}>
                                <div class="content-head">${item.question}</div>
                                <div class="content-inner">我的答案：<span class="content-answer">${item.answer}</span></div>
                            </div>`
                }else{
                    list +=`<div class="content" data-idx=${item.id}>
                                <div class="content-head">${item.question}</div>
                                <div class="upload">
                                    <div class="content-input"><input type="text" placeholder="请输入答案"></div>
                                    <img  class="up_answer" src="image/upload.png" alt="提交答案">
                                </div>
                            </div>`
                }

                center_side.innerHTML = list;

            })
            eventBinding()
        })
    }

    function studentAnswer(questionId) {
        var ans = $(`#center-side .card[data-idx=${questionId}] .answer_input`).val().trim();
        if(ans!=''){
            user.answerQuestion(ans,questionId,function () {
                toast.showMsg('答案提交成功',1000);
                studentGetVote(courseId);
            })
        }else{
            toast.showMsg('请输入内容再提交',1000);
        }

    }
    function m_studentAnswer(questionId) {
        var ans = $(`#question .content[data-idx=${questionId}] .content-input input`).val().trim();
        if(ans!=''){
            user.answerQuestion(ans,questionId,function () {
                toast.showMsg('答案提交成功',1000);
                m_studentGetVote(courseId);
            })
        }else{
            toast.showMsg('请输入内容再提交',1000);
        }
    }

    //其他方法
    //规格化文件大小
    function formatSize(size) {
        var s = size;
        var unit = 'B';
        if(s>=1024){
            s = s/1024;
            unit = 'KB';
            if(s>=1024){
                s = s/1024;
                unit = 'MB';
            }
        }
        return s.toFixed(2)+unit
    }



    return {
        eventBinding:eventBinding,
        showNotice:showNotice,
        postNotice:postNotice,
        deleteNotice:deleteNotice,
        uploadFile:uploadFile,
        downloadFile:downloadFile,
        showFile:showFile,
        teacherGetVote:teacherGetVote,
        studentGetVote:studentGetVote,
        startVote:startVote,
        endVote:endVote,
        _question:_question,
        m_studentAnswer:m_studentAnswer,
        m_studentGetVote:m_studentGetVote,
        m_showFile:m_showFile,
        m_showNotice:m_showNotice

    }
});